var express = require("express");
var router = express.Router();
var connection = require("./connect.js");
var url = require("url");
// 登录
router.get("/api/login", function(req, res) {
  var path_url = url.parse(req.url, true);
  var query = path_url.query;
  var username = query.username;
  var password = query.password;

  var sql = "select count(*) from userinfo where uname=? and password=?";
  var arr = [username, password];
  connection(sql, arr, function(data, tmp) {
    var effectCount = JSON.parse(JSON.stringify(data))[0]['count(*)'];
    console.log("符合条件的结果有" + effectCount + "条记录");
    if (effectCount == 1) {
      console.log(username + ':登陆成功')
      res.send("登陆成功")
    } else {
      console.log(username + ':登录失败')
      res.send("登录失败")
    }
  })
})

// 注册
router.get("/api/register", function(req, res) {
  var path_url = url.parse(req.url, true);
  var query = path_url.query;
  var username = query.username;
  var password = query.password;

  var sql = "INSERT INTO userinfo(id,uname,password) values(null,?,?)";
  var arr = [username, password];
  connection(sql, arr, function(data) {
    if (data.affectedRows) {
      res.send({
        msg: '注册成功'
      })
    } else {
      res.send({
        msg: '注册失败'
      })
    }
  })
})


// 注册验证
router.get("/api/check", function(req, res) {
  var path_url = url.parse(req.url, true);
  var query = path_url.query;
  var username = query.username;
  var password = query.password;

  var sql = "select count(*) from userinfo where uname=? and password=?";
  var arr = [username, password];
  connection(sql, arr, function(data, tmp) {
    var effectCount = JSON.parse(JSON.stringify(data))[0]['count(*)'];
    console.log("符合条件的结果有" + effectCount + "条记录");
    if (effectCount == 1) {
      console.log(username + ':已注册')
      res.send("已注册")
    } else {
      console.log(username + ':可注册')
      res.send("可注册")
    }
  })
})


// add cart
router.get("/api/addcart", function(req, res) {
  var path_url = url.parse(req.url, true);
  var query = path_url.query;
  var gname = query.gname;
  var gprice = query.gprice;
  var gimg = query.gimg;
  var gdesc = query.gdesc;
  var gnum = query.gnum;
  var gid = query.gid;

  var sql = "INSERT INTO cart(id,goodsname,goodsprice,goodsimg,goodsdesc,goodsnum,goodsid) values(null,?,?,?,?,?,?)";
  var arr = [gname,gprice,gimg,gdesc,gnum,gid];
  connection(sql, arr, function(data) {
    if (data.affectedRows) {
      res.send({
        code: '0',
        msg: '添加成功'
      })
    } else {
      res.send({
        code: '1',
        msg: '添加失败'
      })
    }
  })
})

module.exports = router;